<template>
    <div>
        <!-- 面包屑导航 -->
        <div class="page_top">
            <div class="left_btn" @click="back">
                <img src="../../assets/image/back.png" alt="" />
            </div>
            <crumbs basetitle="财务" title="返利管理"></crumbs>
        </div>
        <div class="tabcontentbox">
            <div class="formbox">
                <div class="top">
                    <div class="toptext" style="font-weight: 700;">长期保返利</div>
                    <div class="flexcenterbox">
                        <div class="clear" @click="clearform">
                            <img src="../../assets/image/容器.png" alt="">
                            <span>清除</span>
                        </div>
                    </div>
                </div>
                <div class="formcontent">
                    <div class="form">
                        <div class="formitem">
                            <div class="lable">公司名称：</div>
                            <el-select clearable style="margin-right: 52px;width:265px" v-model="companyid" filterable remote reserve-keyword
                                    @change="getinsurerebatecondition" placeholder="请输入公司名称" :remote-method="remoteMethod"
                                    :loading="loading">
                                    <el-option v-for="item in companylist" :key="item.id" :label="item.companyName"
                                    :value="item.id" />
                                </el-select>
                        </div>
                        <div class="formitem">
                            <div class="lable">返利条件：</div> <el-select @change="getinsurerebatecondition"
                                v-model="rebatecondition" class="m-2" style="width:200px" placeholder="请选择返利条件">
                                <el-option label="不满足结算条件" value="1" />
                                <el-option label="未结算" value="2" />
                                <el-option label="已结算" value="3" />
                            </el-select>
                        </div>
                        <div class="formitem">
                            <div class="lable">投保月份：</div> <el-date-picker @change="getinsurerebatecondition"
                                v-model="monthvalue" type="month" value-format="YYYY-MM" placeholder="请选择投保月份" />
                        </div>
                    </div>
                    <el-button type="primary" size="default" @click="exportlist" style="margin-top: 10px;" class="my_btn">
                        <img style="width: 16px;margin-right: 6px;" src="../../assets/image/导出@2x.png" alt="">
                        导出数据
                    </el-button>
                </div>
            </div>
        </div>
        <div class="tabcontentbox" style="margin-top: -32px;">
            <div class="accounttable">
                <div class="tableborder">
                    <el-table :data="financeReceiptdata" style="width: 100%; margin-top: 0" :header-cell-style="{
                        background: '#FAFAFC',
                        color: '#202536',
                    }">
                        <el-table-column prop="companyName" label="客户名称" />
                        <el-table-column prop="ensureMonth" label="月份" />
                        <el-table-column prop="totalMonthCount" label="月在保人数" />
                        <el-table-column v-for="item in planColumns" :key="item.code" :column-key="item.code"
                            :label="item.label" min-width="160">
                            <template #default="scope">
                                <div
                                    v-if="scope.row.planRebateInfoList.filter((v: any) => v.insurCompanyPlanCode == scope.column.columnKey).length > 0">
                                    <div>1-3类：{{ scope.row.planRebateInfoList.filter((v: any) => v.insurCompanyPlanCode ==
                                        scope.column.columnKey)[0].ensureCount }} x {{
        scope.row.planRebateInfoList.filter((v: any) => v.insurCompanyPlanCode ==
            scope.column.columnKey)[0].rebatePrice }}</div>
                                    <div>4类：{{ scope.row.planRebateInfoList.filter((v: any) => v.insurCompanyPlanCode ==
                                        scope.column.columnKey)[0].ensureCountFour }} x {{
        scope.row.planRebateInfoList.filter((v: any) => v.insurCompanyPlanCode ==
            scope.column.columnKey)[0].rebatePriceFour }}</div>
                                    <div>返利：{{ (scope.row.planRebateInfoList.filter((v: any) => v.insurCompanyPlanCode ==
                                        scope.column.columnKey)[0].rebateAmount +
                                        scope.row.planRebateInfoList.filter((v: any) =>
                                            v.insurCompanyPlanCode == scope.column.columnKey)[0].rebateAmountFour).toFixed(2) }}
                                    </div>
                                </div>
                            </template>
                        </el-table-column>
                        <el-table-column prop="totalMonthRebateAmount" label="返利金额" />
                        <el-table-column prop="area" label="凭证">
                            <template #default="scope">
                                <span v-if="scope.row.rebateVoucher != '' && scope.row.rebateStatus===3" style="color: #3e5ff5; cursor: pointer"
                                    @click="checkvoucher(scope.row.rebateVoucher)">查看凭证</span>
                                <span v-else>--</span>
                            </template>
                        </el-table-column>
                        <el-table-column label="结算状态">
                            <template #default="scope">
                                <div v-if="scope.row.rebateStatus === 2">未结算</div>
                                <div v-else-if="scope.row.rebateStatus === 1" class="origin">不满足结算条件</div>
                                <div v-else-if="scope.row.rebateStatus === 3" class="gray">已结算</div>
                            </template>
                        </el-table-column>
                        <el-table-column label="操作">
                            <template #default="scope">
                                <div class="flexbox">
                                    <span class="blue" style="margin-right: 6px;cursor: pointer;"
                                        @click="companyexport(scope.row)">导出</span>
                                    <span v-show="scope.row.rebateStatus === 2" class="blue" @click="fljstcopen(scope.row)"
                                        style="margin-right: 6px;cursor: pointer;">结算</span>
                                </div>
                            </template>
                        </el-table-column>
                    </el-table>
                </div>
                <div class="paginationborder">
                    <pagination :total="financeReceipttotal" :currentPage="financeReceiptpagenum"
                        :pageSize="financeReceiptpagesize" @SizeChange="changefinanceReceiptpagesize"
                        @CurrentChange="changefinanceReceiptpagenum"></pagination>
                </div>
            </div>
        </div>
        <!-- 产看凭证弹出框 -->
        <el-dialog v-model="dialogvoucherVisible" title="凭证查看" :width="isMobile ? '580' : '30%'">
            <div style="text-align: center">
                <img style="width: 100%" crossorigin="anonymous" :src="voucherimg" alt="" />
            </div>
        </el-dialog>
        <!-- 返利结算弹出框 -->
        <el-dialog v-model="fljstc" title="返利结算" width="450">
            <div class="m-t">系统返利金额<span class="ck" style="margin-left: 8px;">参考值</span></div>
            <div class="m-t">
                <el-input style="width: 200px;" v-model="ckflz" disabled></el-input>
            </div>
            <div class="m-t">凭证返利金额<span class="red">*</span></div>
            <div class="m-t">
                <el-input-number style="width: 314px;" placeholder="请输入金额" v-model="flnum" :min="1" />
            </div>
            <div class="m-t">上传凭证<span class="red">*</span></div>
            <el-upload ref="uploadRef" class="upload-demo" :file-list="dayfileList" :on-change="dayonChange"
                accept=".png,.jpeg,.jpg,.pdf" :limit="1" :auto-upload="false">
                <template #trigger>
                    <el-button type="primary" class="my_btn">选择文件</el-button>
                </template>
                <template #tip>
                    <div class="el-upload__tip">
                        大小限制5MB，支持png、jpeg、jpg、pdf格式文件
                    </div>
                </template>
            </el-upload>
            <div class="flexcenterbox" style="margin-top: 10px;">
                <el-button class="my_cancelbtn" @click="cancelsubmit">取消</el-button>
                <el-button class="my_btn" @click="jssure">确定</el-button>
            </div>
        </el-dialog>
    </div>
</template>

<script setup lang="ts">
import { ElMessage } from 'element-plus'
import { ref, reactive, computed, watch, onMounted, onActivated} from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { ffjsapi, companyexportflsj, exportflsj, getcompanyapi, getinsurerebateconditionapi } from '../../api/api'
import baseurl from '../../api/env'
const isMobile = ref((window as any).isMobile)

const router = useRouter()
const route = useRoute()
const fljstc = ref(false)
const flnum = ref<any>(null)
const ckflz = ref('')
const uploadRef = ref()
const cancelsubmit = () => {
    fljstc.value = false
    ckflz.value = ''
    flnum.value = null
    selectedImage.value = null
    uploadRef.value.clearFiles()
}
const remoteMethod = (query: string) => {
    if (query) {
        loading.value = true
        getcompany(query)
    } else {
        companylist.value = []
    }
}
const loading = ref(false)
const ffjs = async () => {
    const res: any = await ffjsapi({
        companyId: jscompanyId.value,
        ensureMonth: jsensureMonth.value,
        voucherAmount: jsvoucherAmount.value,
        rebateAmount: flnum.value,
        voucherUrl: selectedImage.value.split(',')[1],
        count: jscount.value
    })
    console.log(res, '返费结算')
    if (res.code === 200) {
        cancelsubmit()
        getinsurerebatecondition()
        ElMessage({
            type: 'success',
            message: '操作成功'
        })
    }
}
const dayfileList = ref([])

const dayonChange = (file: any, fileListVal: any) => {
    console.log(file)
    const reader = new FileReader()
    reader.onload = (event: any) => {
        const url = event.target.result
        console.log(url)
        selectedImage.value = url
    }
    reader.readAsDataURL(file.raw)
    dayfileList.value = fileListVal
}
const selectedImage = ref<any>(null)
onMounted(() => {
    // const y = new Date().getFullYear()
    // const m = new Date().getMonth()
    // monthvalue.value = `${y}-${m >= 10 ? m : '0' + m}`
    // console.log(monthvalue.value)
    // getinsurerebatecondition()
})
onActivated(() => {
    const y = new Date().getFullYear()
    const m = new Date().getMonth()
    monthvalue.value = `${y}-${m >= 10 ? m : '0' + m}`
    console.log(monthvalue.value)
    getinsurerebatecondition()
})
const jssure = () => {
    if (flnum.value === null) {
        ElMessage({
            message: '请输入凭证返利金额',
            type: 'warning'
        })
        return
    }
    if (selectedImage.value === null) {
        ElMessage({
            message: '请选择文件',
            type: 'warning'
        })
        return
    }
    ffjs()
}
const jsensureMonth = ref('')
const jsvoucherAmount = ref('')
const jscount = ref(0)
const jscompanyId = ref(0)
const fljstcopen = (val: any) => {
    ckflz.value = val.totalMonthRebateAmount
    jsensureMonth.value = val.ensureMonth
    jsvoucherAmount.value = val.totalMonthRebateAmount
    jscount.value = val.totalMonthCount
    jscompanyId.value = val.companyId
    console.log(val)
    fljstc.value = true
}
const companyexport = (val: any) => {
    companyexportflsjfn(val.companyId, val.ensureMonth)
}
// 查看凭证弹出框
const dialogvoucherVisible = ref(false)
const voucherimg = ref('')
const checkvoucher = (src: string) => {
    voucherimg.value = src
    dialogvoucherVisible.value = true
}
const companyexportflsjfn = async (id: any, ensureMonth: any) => {
    const res: any = await companyexportflsj({
        companyId: id,
        ensureMonth: ensureMonth
    })
    console.log(res)
    window.location.href = baseurl + '/common/download?delete=true&fileName=' + res
}
const exportlist = () => {
    exportflsj({
        rebateStatus: rebatecondition.value,
        ensureMonth: monthvalue.value,
        companyId: companyid.value,
    }).then((res: any) => {
        console.log(res, '导出返利数据')
        window.location.href = baseurl + '/common/download?delete=true&fileName=' + res
    })
}
const getinsurerebatecondition = async () => {
    const res: any = await getinsurerebateconditionapi({
        pageNum: financeReceiptpagenum.value,
        pageSize: financeReceiptpagesize.value,
        companyId: companyid.value,
        ensureMonth: monthvalue.value?monthvalue.value:'',
        rebateStatus: rebatecondition.value,
    })
    console.log(res, '返利数据')
    if (res.rows != null && res.rows.length > 0) {
        financeReceiptdata.value = res.rows
        if (res.rows != null && res.rows.length > 0) {
            res.rows.map((v: any, i: number) => {
                v.planRebateInfoList.length > 0 &&
                    v.planRebateInfoList.forEach((sv: any, sk: number) => {
                        if (planColumns.value.length == 0 || !planColumns.value.map((plan: any, k: number) => plan.code).includes(sv.insurCompanyPlanCode)) {
                            planColumns.value.push({ label: sv.insurCompanyPlanName, code: sv.insurCompanyPlanCode })
                        }
                    })
            })
        }
    } else {
        financeReceiptdata.value = []
    }
    financeReceipttotal.value = res.total
}
const planColumns = ref<any>([])
const monthvalue = ref('')
const rebatecondition = ref('')
// 获取公司列表
const getcompany = async (val:any) => {
    const res: any = await getcompanyapi(val)
    console.log(res, '获取公司列表')
    companylist.value = res
    loading.value = false
}
const companyid = ref<any>(null)
const companylist = ref<any>([])
const clearform = () => {
    companyid.value = null
    monthvalue.value = ''
    rebatecondition.value = ''
    getinsurerebatecondition()
}
const financeReceiptpagesize = ref(10)
const financeReceiptpagenum = ref(1)
const financeReceipttotal = ref(0)
const financeReceiptdata = ref<any>([])
const changefinanceReceiptpagesize = (val: any) => {
    financeReceiptpagesize.value = val
    financeReceiptpagenum.value = 1
    getinsurerebatecondition()
}
const changefinanceReceiptpagenum = (val: any) => {
    financeReceiptpagenum.value = val
    getinsurerebatecondition()
}
const back = () => {
    window.history.back()
}
</script>

<style lang="scss" scoped>
.formbox {
    background-color: #ffffff;
    border-top-right-radius: 8px;
    width: 100%;
    box-sizing: border-box;
    padding: 0 8px;
    border-radius: 8px;

    .formcontent {
        padding: 0 24px 16px;
        width: 100%;
        box-sizing: border-box;
        display: flex;
        align-items: center;
        justify-content: space-between;

        .form {
            display: flex;
            align-items: center;
        }

        .formitem {
            margin-top: 16px;
            margin-right: 50px;
            display: flex;
            align-items: center;

            .formitemflexone {
                display: flex;
                align-items: center;
                flex: 1;
            }

            .lable {
                min-width: 70px;
                font-size: 14px;
                color: #202536;
                margin-right: 8px;
                text-align: right;
            }
        }
    }

    .top {
        width: 100%;
        box-sizing: border-box;
        display: flex;
        justify-content: space-between;
        padding: 16px 8px;
        align-items: center;
        border-bottom: 1px solid #F4F4F7;

        .toptext {
            color: #3D3D3D;
            font-size: 14px;
        }

        .utils {
            display: flex;
            align-items: center;
        }

        .clear {
            cursor: pointer;
            margin-right: 20px;
            margin-left: 24px;
            color: #9497B1;
            font-size: 14px;

            img {
                width: 16px;
                height: 16px;
                margin-right: 6px;
                margin-bottom: -3px;
            }
        }
    }
}

.tabcontentbox {
    padding: 16px;
}

.accounttable {
    width: 100%;
    box-sizing: border-box;
    background-color: #ffffff;
    border-radius: 8px;
    padding: 24px;
    margin-top: 16px;
}

.tableborder {
    border: 1px solid #EAEAEF;
    border-bottom: none !important;
}

.origin {
    color: #FF7642;
}

.gray {
    color: #9497B1;
}

.blue {
    color: #3E5FF5;
}

.ck {
    font-size: 11px;
    color: #3D3D3D;
    opacity: .5;
}

.red {
    color: red;
}

.m-t {
    margin-bottom: 20px;
}
</style>
